package com.keyinong.fragment;

import java.util.ArrayList;

import org.apache.http.Header;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.Fragment;
//import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.keyinong.restaurant.R;
import com.keyinong.restaurant.ScanActivity;
import com.keyinong.restaurant.dapter.OrderAdapter;
import com.keyinong.restaurant.dapter.PickupAdapter;
import com.keyinong.restaurant.entity.OrderBean;
import com.keyinong.restaurant.entity.OrderEntity;
import com.keyinong.restaurant.entity.OrderBean.OrderInfo;
import com.keyinong.restaurant.tools.HttpTools;
import com.keyinong.restaurant.view.MainActivity;
import com.keyinong.restaurant.view.OrderDetailActivity;
import com.loopj.android.http.JsonHttpResponseHandler;

public class ShouyeFragment extends Fragment{
	private static String TAG = MainActivity.class.getSimpleName(); 	
	/**上下拉刷新*/
	private PullToRefreshListView list_order;
	HttpTools httpTools = null;
	private ArrayList<OrderInfo> orderlist;
	
	int page = 10;
	int offset = 0;
	private String token;
	private String state;
	Gson gson=new Gson();
	/**扫一扫*/
	private ImageButton btn_saoyisao;
	
	// 语音合成对象
		private SpeechSynthesizer mTts;
		// 默认发音�?
		private String voicer = "xiaoyan";
		private String[] mCloudVoicersEntries;
		private String[] mCloudVoicersValue ;
		private Toast mToast;
		// 引擎类型
		private String mEngineType = SpeechConstant.TYPE_CLOUD;

		private SharedPreferences mSharedPreferences;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_shouye, null);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
//		orderlist = new ArrayList<OrderEntity>();
		orderlist=new ArrayList<OrderBean.OrderInfo>();
		list_order=(PullToRefreshListView)getView().findViewById(R.id.list_order);
		list_order.setMode(Mode.BOTH);
		list_order.setOnRefreshListener(onrefresh);
		list_order.setOnItemClickListener(itemclicke);
		
		// 初始化合成对�?
				mTts = SpeechSynthesizer.createSynthesizer(getActivity(), mTtsInitListener);

				// 云端发音人名称列�?
				mCloudVoicersEntries = getResources().getStringArray(R.array.voicer_cloud_entries);
				mCloudVoicersValue = getResources().getStringArray(R.array.voicer_cloud_values);

				mToast = Toast.makeText(getActivity(),"",Toast.LENGTH_SHORT);

				setParam();
//		handler.postDelayed(runnable, 10000);
	}
	
	@Override
	public void onStart() {
		super.onStart();
		myOrder();
	}
	
	/**
	 * 合成回调监听�?
	 */
	private SynthesizerListener mTtsListener = new SynthesizerListener() {
		@Override
		public void onSpeakBegin() {
			//			showTip("�?始播�?");
		}
		@Override
		public void onSpeakPaused() {
			//			showTip("暂停播放");
		}
		@Override
		public void onSpeakResumed() {
			//			showTip("继续播放");
		}
		@Override
		public void onBufferProgress(int percent, int beginPos, int endPos,
				String info) {
			// 合成进度
			//			mPercentForBuffering = percent;
			//			showTip(String.format(getString(R.string.tts_toast_format),
			//					mPercentForBuffering, mPercentForPlaying));
		}

		@Override
		public void onSpeakProgress(int percent, int beginPos, int endPos) {
			// 播放进度
			//			mPercentForPlaying = percent;
			//			showTip(String.format(getString(R.string.tts_toast_format),
			//					mPercentForBuffering, mPercentForPlaying));
		}

		@Override
		public void onCompleted(SpeechError error) {
			if (error == null) {
				//				showTip("播放完成");
			} else if (error != null) {
				showTip(error.getPlainDescription(true));
			}
		}

		@Override
		public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {

		}
	};

	private void showTip(final String str) {
		mToast.setText(str);
		mToast.show();
	}

	private void TTs() {
		String sayContext = "您有新的订单请及时处理";
		int code = mTts.startSpeaking(sayContext, mTtsListener);
		//		/** 
		//		 * 只保存音频不进行播放接口,调用此接口请注释startSpeaking接口
		//		 * text:要合成的文本，uri:�?要保存的音频全路径，listener:回调接口
		//		*/
		//		String path = Environment.getExternalStorageDirectory()+"/tts.pcm";
		//		int code = mTts.synthesizeToUri(text, path, mTtsListener);

		if (code != ErrorCode.SUCCESS) {
			if(code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED){
				//未安装则跳转到提示安装页�?
				//mInstaller.install();
			}else {
				showTip("语音合成失败,错误码: " + code);	
			}
		}
	}
	
	/**
	 * 初始化监听�??
	 */
	private InitListener mTtsInitListener = new InitListener() {
		@Override
		public void onInit(int code) {
//			Log.d(TAG, "InitListener init() code = " + code);
			if (code != ErrorCode.SUCCESS) {
				showTip("初始化失败,错误码："+code);
			} else {
				// 初始化成功，之后可以调用startSpeaking方法
				// 注：有的�?发�?�在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成�?
				// 正确的做法是将onCreate中的startSpeaking调用移至这里
			}		
		}
	};

	/**
	 * 参数设置
	 * @param param
	 * @return 
	 */
	private void setParam(){
		// 清空参数
		mTts.setParameter(SpeechConstant.PARAMS, null);
		// 根据合成引擎设置相应参数
		if(mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
			mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
			// 设置在线合成发音�?
			mTts.setParameter(SpeechConstant.VOICE_NAME,voicer);
		}else {
			mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
			// 设置本地合成发音�? voicer为空，默认�?�过语音+界面指定发音人�??
			mTts.setParameter(SpeechConstant.VOICE_NAME,"");
		}
		//设置合成语�??
		mTts.setParameter(SpeechConstant.SPEED, "50");
		//设置合成音调
		mTts.setParameter(SpeechConstant.PITCH, "50");
		//设置合成音量
		mTts.setParameter(SpeechConstant.VOLUME,"50");
		//设置播放器音频流类型
		mTts.setParameter(SpeechConstant.STREAM_TYPE,"3");

		// 设置播放合成音频打断音乐播放，默认为true
		mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");

		// 设置合成音频保存路径，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
		mTts.setParameter(SpeechConstant.PARAMS,"tts_audio_path="+Environment.getExternalStorageDirectory()+"/test.pcm");
	}
	
	
	private Handler handler = new Handler();
//	private Runnable runnable = new Runnable() {
//		public void run() {
//			try {
//				this.update();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			handler.postDelayed(this, 60000);// 间隔60秒刷新一�?
//		}
//		void update() throws IOException {
//			onrefresh.onPullDownToRefresh(list_order);
//		}
//	}; 
	
	/** 上下拉刷�? */
	private OnRefreshListener2<ListView> onrefresh = new OnRefreshListener2<ListView>() {

		@Override
		public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
			offset = 0;
			orderlist.clear();
			httpTools.getSaleOrders(token, page + "",offset+"",
					new JsonGetSaleOrders());
		}

		@Override
		public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
			offset += page;
			httpTools.getSaleOrders(token, page + "",offset+"",
					new JsonGetSaleOrders());
			// setSection();
			// adapter.notifyDataSetChanged();
		}

	};
	
	private OnItemClickListener itemclicke = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view,final int position,
				long id) {
//			Log.e("lh", "position=="+position);
			Intent intent = new Intent();
			intent.putExtra("id", orderlist.get(position-1).getId());
			intent.setClass(getActivity(), OrderDetailActivity.class);
			startActivity(intent);
		}
	};
	
	/**所有订单*/
	private void myOrder() {
		SharedPreferences sp = getActivity().getSharedPreferences("spReg",
				Context.MODE_PRIVATE);
		token = sp.getString("token", "");
//		Log.i("zq", "token--"+token);
//		TTs();
		if (httpTools == null) {
			httpTools = new HttpTools(getActivity());
		}
//		httpTools.order(token, page + "", offset + "", "0","0",new JsonMyOrder());
		httpTools.getSaleOrders(token, page + "",offset+"",
				new JsonGetSaleOrders());
	}
	
	private class JsonGetSaleOrders extends JsonHttpResponseHandler{

		@Override
		public void onSuccess(int statusCode, Header[] headers,
				JSONObject response) {
			super.onSuccess(statusCode, headers, response);
			list_order.onRefreshComplete();
//			Log.e("lh", "GetSaleorder---" + response.toString());
			try {
				
				OrderBean  order=gson.fromJson
						(response.toString(), OrderBean.class);
				if(order.isCode()){
					orderlist=order.getData().getOrders();
					list_order.setAdapter(new PickupAdapter
							(getActivity(),orderlist));
					list_order.getRefreshableView().setSelection(offset);
					
				}else{
					Toast.makeText(getActivity(), order.getMsg(), 
		        			Toast.LENGTH_SHORT).show();
				}
			} catch (Exception e) {
				Toast.makeText(getActivity(), "获取订单信息失败", 
	        			Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			}
		}
		
		
		@Override
		public void onFailure(int statusCode, Header[] headers,
				String responseString, Throwable throwable) {
			super.onFailure(statusCode, headers, responseString, throwable);
			list_order.onRefreshComplete();
			Toast.makeText(getActivity(), "获取订单信息失败", 
        			Toast.LENGTH_SHORT).show();
		}

		
	}
	
//	private class JsonMyOrder extends JsonHttpResponseHandler {
//		@Override
//		public void onSuccess(int statusCode, Header[] headers,
//				JSONObject response) {
//			super.onSuccess(statusCode, headers, response);
//			Log.e("zq", "order---" + response.toString());
//			try {
//				boolean code = response.getBoolean("code");
//				if (code == true) {
//					JSONObject object = response.getJSONObject("data");
////					String isnew = object.getString("isnew");
//					JSONArray array = object.getJSONArray("orders");
//					for (int i = 0; i < array.length(); i++) {
//						JSONObject object2 = array.getJSONObject(i);
//						String id = object2.getString("id");
//						String receive_time = object2.getString("receive_time");
//						state = object2.getString("state");
//						String name = object2.getString("name");
//						String phone = object2.getString("phone");
//						String address = object2.getString("address");
//						String paymodeid = object2.getString("paymodeid");
//						String recmode = object2.getString("recmode");
////						Log.i("zq", "state---"+state);
//						if(state.equals("null")){
//							Toast.makeText(getActivity(), "没有订单", Toast.LENGTH_SHORT).show();
//						}else if(state.equals("1")){
//							TTs();
//						}
//						orderlist.add(new OrderEntity(id, receive_time, state, name, phone, address,recmode,paymodeid));
//					}
////					Log.i("zq", "isnew---"+isnew);
//					
//						OrderAdapter adapter = new OrderAdapter(getActivity(), orderlist);
//						list_order.setAdapter(adapter);
//						list_order.getRefreshableView().setSelection(offset);
//						
//				} else {
//					String msg = response.getString("msg");
//					Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
//				}
//				list_order.onRefreshComplete();
//			} catch (JSONException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
//        
//	}
	
}
